<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="角色名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色名称" prop="zhCnName"/>
        <el-table-column label="角色编码（英文）" prop="enName"/>
        <el-table-column fixed="right" label="操作"  min-width="450" width="450">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openRoleDialog(scope.row)"
            ><i class="el-icon-set-up"></i> 设置角色用户</el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openResourceDialog(scope.row)"
            ><i class="el-icon-set-up"></i> 设置角色资源</el-button>
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="500px"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="角色名称" prop="zhCnName">
          <el-input v-model="formData.zhCnName" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色编码（英文）" prop="enName">
          <el-input v-model="formData.enName" placeholder="请输入角色编码" :disabled="formData.id"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配用户弹窗  -->
    <el-dialog
      :visible.sync="userDialogVisible"
      :title="'【' + checkedRole.zhCnName + '】角色分配用户'"
      width="800px"
    >
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-table
					ref="multipleTable"
          v-loading="loading"
          :data="userList"
          highlight-current-row
          border
          @selection-change="handleSelectionUserChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户名称" prop="name"/>
          <el-table-column label="用户登录名" prop="loginName"/>
					<el-table-column label="微信昵称" prop="nickName"/>
        </el-table>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="allocateUsers">确 定</el-button>
          <el-button @click="closeRoleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配资源弹窗  -->
    <el-dialog
      :visible.sync="resourceDialog.visible"
      :title="'【' + checkedRole.zhCnName + '】角色分配资源'"
      width="800px"
    >
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-table
        ref="multipleTable1"
        v-loading="loading"
        :data="resourceList"
				row-key="id"
				:tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        highlight-current-row
        border
        @selection-change="handleResourceSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="资源名称" prop="name" min-width="200"/>
        <el-table-column label="类型" prop="type"/>
      </el-table>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="allocateResources">确 定</el-button>
          <el-button @click="closeResourceDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>

import userApi from '@/api/system/user'
import roleApi from '@/api/system/role'
import resourceApi from '@/api/system/resource'
export default {
	name: 'userIndex',
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      userDialogVisible: false,
      userList: [],
      checkedRole: {},
      dialog: {},
      formData: {},
      rules: {},
      selectUserIdArr: [],

      resourceDialog: {},
      resourceList: [],
      resourceIds: [],
		};
	},
  methods: {
    allocateResources () {
      let resourceIds = this.resourceIds;
      console.log(resourceIds)
      roleApi.allocateResources(this.checkedRole.id, resourceIds).then(res => {
        this.$message({message: '角色资源设置成功！', type: 'success'});
        this.closeResourceDialog();
      })
    },
    handleResourceSelectionChange (val) {
      this.resourceIds = [];
      val.forEach(v => {
        this.resourceIds.push(v.id);
      });
    },
    openResourceDialog (row) {
      this.$set(this.resourceDialog, 'visible', true);
      this.checkedRole = row;
      roleApi.getResources(row.id).then(r => {
        let roleResources = r.data.resources;
        resourceApi.list().then((res) => {
          let data = res.data;
          this.resourceList = data;
          this.loading = false;
          console.log(roleResources)
          if (roleResources.length != 0) {
            let roleResourcesId = [];
            roleResources.forEach(v => {
              roleResourcesId.push(v.id)
            })
            this.$nextTick(function () {
              this.resourceList.forEach((resource) => {
                console.log(resource)
                if (roleResourcesId.indexOf(resource.id) != -1) {
                  this.$refs.multipleTable1.toggleRowSelection(resource, true);
                }
                if (resource.children && resource.children.length != 0) {
                  resource.children.forEach(resourceC => {
                    if (roleResourcesId.indexOf(resourceC.id) != -1) {
                      this.$refs.multipleTable1.toggleRowSelection(resourceC, true);
                    }
                  })
                }
            })})
          }

        }).catch(() => {});
      })
      
    },
    closeResourceDialog () {
      this.$set(this.resourceDialog, 'visible', false);
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      roleApi.page(params).then((res) => {
        let data = res.data;
        this.dataList = data.content;
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        roleApi.update(this.formData).then((res) => {
          this.$message({message: '角色更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        roleApi.add(this.formData).then((res) => {
          this.$message({message: '角色添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },

    openRoleDialog(row) {
      this.userDialogVisible = true;
      this.checkedRole = row;
      
      userApi.list().then((res) => {
        this.userList = res.data;
				let that = this;
				this.$nextTick(function () {
					this.userList.forEach((user) => {
						let roles = user.roles;
						let roleName = [];
						if (roles.length > 0) {
							roles.forEach((r) => {
								roleName.push(r.enName);
							});
							if (roleName.indexOf(row.enName) != -1) {
								that.$refs.multipleTable.toggleRowSelection(user, true);
							}
						}
				})})
      });
    },
    closeRoleDialog() {
      this.userDialogVisible = false;
      this.userList = [];
    },

    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑角色');
        roleApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;
        });
      } else {
        this.$set(this.dialog, 'title', '新增角色');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        roleApi.delete(id).then((res) => {
          this.$message({message: '角色删除成功！', type: 'success'});
					this.handleQuery();
        }).catch(() => {});
      } else {

        this.$message.error('暂不支持批量删除角色！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionUserChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectUserIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
    allocateUsers() {
      let roleId = this.checkedRole.id;
      let userIds = this.selectUserIdArr;
      roleApi.allocateUsers(roleId, userIds).then((res) => {
        this.$message({message: '用户角色设置成功！', type: 'success'});
        this.closeRoleDialog();
      });
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>